import React, { useState, useEffect, useRef } from 'react';
import styles from '../index.less';
import { QuestionCircleOutlined, VerticalAlignTopOutlined } from '@ant-design/icons';
import { Tabs, Input, Tooltip, Button, Upload, message } from 'antd';
import { doFetch } from '@/utils/doFetch';
import { useRequest } from 'ahooks';
import ViewFileList from './viewfilelist';

const { TextArea } = Input;

function beforeUpload(file) {
  let size = 10;
  // const isJpgOrPng = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png';

  // if (!isJpgOrPng && item.listType == 'img') {
  //   message.error('只能上传.jpg/.jpeg/.png图片!');
  // }
  const isLt3M = file.size / 1024 / 1024 < size;
  if (!isLt3M) {
    message.error('文件大小须小于' + size + 'MB!');
  }
  return isLt3M;
}

function CUNote({ defaultValue, company_id, refresh, setDefaultValue }) {
  const { run, loading } = useRequest(doFetch, {
    manual: true,
    formatResult: (res) => res,
    onSuccess: (result, params) => {
      message.destroy();
      if (result.code == 0) {
        message.success('操作成功！');
        refresh?.();
        setFilelist([]);
        setContent(null);
      } else {
        message.error(result.message);
      }
    },
  });

  const title = defaultValue ? '编辑记录' : '新增记录';
  const [collspan, setCollspan] = useState(false);
  const [filelist, setFilelist] = useState([]); //文件列表
  const [content, setContent] = useState(null); //内容

  const props = {
    name: 'file',
    multiple: true,
    action: window?.dataconfig?.serverURL,
    showUploadList: false,
    beforeUpload: beforeUpload,
    onChange(info) {
      const { file, fileList } = info;
      const { status } = file;
      if (status !== 'uploading') {
      }
      if (status === 'done') {
        const uploadlist = fileList
          .filter((it) => it.response && it.response.code == 0)
          ?.map((it) => it?.response?.data?.file);
        setFilelist(uploadlist);
      } else if (status === 'error') {
        message.error(`${info.file.name} 上传失败.`);
      }
    },
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files);
    },
  };

  useEffect(() => {
    if (defaultValue) {
      setCollspan(false);
      setFilelist(defaultValue?.filelist ?? []);
      setContent(defaultValue?.content ?? null);
      // edit
    } else {
      // add
      setCollspan(false);
      setFilelist([]);
      setContent(null);
    }
  }, [defaultValue]);

  const inputRef = useRef();

  return (
    <div className={styles.actionbar}>
      <div className="spread">
        <span style={{ flex: 1 }}>
          {title}
          {defaultValue && (
            <a
              onClick={() => {
                setDefaultValue(null);
              }}
              style={{ color: '#ff4800', marginLeft: 10 }}
            >
              取消
            </a>
          )}
        </span>
        <div
          className="center animated"
          onClick={() => {
            setCollspan(!collspan);
          }}
        >
          <a>
            {!collspan ? '收起' : '展开'}面板
            <VerticalAlignTopOutlined rotate={!collspan ? 0 : 180} />
          </a>
        </div>
      </div>

      <div
        className={styles.actions}
        style={{
          height: collspan ? 0 : 'auto',
          overflow: 'hidden',
          margin: collspan ? 0 : '10px 0',
        }}
      >
        <div style={{ padding: 16 }}>
          <TextArea
            ref={inputRef}
            style={{ resize: 'none' }}
            bordered={false}
            placeholder="在此添加记录,开启记事本～"
            rows={5}
            value={content}
            onChange={(e) => setContent(e.target.value)}
          />
          <div>
            <ViewFileList
              files={filelist}
              deleteIt={(id) => {
                setFilelist((s) => {
                  const news = JSON.parse(JSON.stringify(s));
                  return news?.filter((its) => its.id !== id);
                });
              }}
            />
          </div>
          <div className="center" style={{ gap: 12, marginTop: 12 }}>
            <div style={{ flex: 1 }} className="resets">
              {!loading && (
                <Upload.Dragger {...props}>
                  <div className="center">
                    <span style={{ textAlign: 'center', flex: 1 }}>
                      拖拽文件到此处或<a>点击上传</a>
                    </span>
                    <div className="center">
                      <Tooltip
                        overlayInnerStyle={{ width: 630 }}
                        title="文件可上传jpg、png、jpeg、doc、docx、xls.xlsx、 pdf.zip.rar类型文件，每次上传不超过10M"
                        placement="bottomRight"
                      >
                        <span>
                          上传说明 &nbsp; <QuestionCircleOutlined />
                        </span>
                      </Tooltip>
                    </div>
                  </div>
                </Upload.Dragger>
              )}
            </div>

            <Button
              type="primary"
              size="large"
              loading={loading}
              onClick={() => {
                if (!content) {
                  message.warn('请填写记事本内容！');
                  inputRef?.current?.focus();
                  return;
                }
                run({
                  url: '/wbn-api/company_note',
                  params: {
                    company_id,
                    content,
                    files: filelist?.map((it) => it.id),
                  },
                });
              }}
            >
              保存
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}

export default CUNote;
